package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.config.WechatProperties;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.MerchantMapper;
import com.sky.mapper.user.UserLoginMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.service.user.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WechatProperties wechatProperties;

    @Autowired
    private UserLoginMapper userLoginMapper;

    /**
     * 用户登录及自动注册
     * @param dto
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        String openId = getOpenId(dto.getCode());
        if (!StringUtils.hasText(openId)){
            throw new BaseException("未获取到openId");
        }
        User user = userLoginMapper.queryByOpenId(openId);
        Optional<User> optional = Optional.ofNullable(user);
        if (optional.isEmpty()){
            User user1 = new User();
            user1.setCreateTime(LocalDateTime.now());
            user1.setOpenid(openId);
            userLoginMapper.insert(user1);
        }
        user = userLoginMapper.queryByOpenId(openId);
        Map<String,Object> param = new HashMap<>();
        param.put("openId",openId);
        param.put("id",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), param);
        Merchant merchant = merchantMapper.queryById(1L);
        UserLoginVO loginVO = new UserLoginVO().builder().id(user.getId())
                .shopId(merchant.getId())
                .openid(openId)
                .token(token)
                .deliveryFee(new BigDecimal(2d))
                .shopAddress(merchant.getShopAddress())
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .build();
        loginVO.setOpenid(openId);
        return loginVO;
    }

    /**
     * 获取openId
     * @param code
     * @return
     */
    private String getOpenId(String code){
        HashMap<String, String> param = new HashMap<>();
        param.put("appid",wechatProperties.getAppId());
        param.put("secret",wechatProperties.getSecret());
        param.put("js_code",code);
        param.put("grant_type","authorization_code");
        String response = HttpClientUtil.doGet(wechatProperties.getUrl(), param);
        JSONObject jsonObject = JSON.parseObject(response);
        String openid = (String) jsonObject.get("openid");
        log.info(openid);
        return openid;

    }
}
